package com.gec.hrm.servlet;

import com.gec.hrm.dao.impl.DocumentDao;
import com.gec.hrm.dao.impl.DocumentDaoImpl;
import com.gec.hrm.pojo.Dept;
import com.gec.hrm.pojo.Document;
import com.gec.hrm.pojo.R;
import com.gec.hrm.pojo.User;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = {"/documentList.action","/upload.action","/addDocument.action","/delDocument.action","/delDocuments.action","/updDocument.action"})
public class DocumentServlet extends HttpServlet {
    public DocumentDao documentDao = new DocumentDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String url = request.getRequestURI();
        System.out.println(url);
        String action = url.substring(url.lastIndexOf("/") + 1);
        System.out.println(action);

        if (action.equals("documentList.action")) {
            documentList(request, response);
        }else if(action.equals("upload.action")){
            upload(request,response);
        }else if(action.equals("addDocument.action")){
            addDocument(request,response);
        }else if(action.equals("delDocument.action")){
            delDocument(request,response);
        }else if(action.equals("delDocuments.action")){
            delDocuments(request,response);
        }else if(action.equals("updDocument.action")){
            updDocument(request,response);
        }
    }

    private void updDocument(HttpServletRequest request, HttpServletResponse response) {
        String title = request.getParameter("title");

        String remark = request.getParameter("remark");
        int id = Integer.parseInt(request.getParameter("id"));
        String fileName=request.getParameter("filename");
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        System.out.println(title);
        System.out.println(fileName);
        String[] res=fileName.split("\\.");
        String fileType=res[1];
        String url="/files/"+fileName;
        System.out.println(fileType);
        Document document=new Document(title,remark,fileName,fileType,url);
        document.setId(id);

        int i = documentDao.updDocument(document);

        try {
            PrintWriter out = response.getWriter();
            if (i > 0) {
                out.print(1);
            } else {
                out.print(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void delDocuments(HttpServletRequest request, HttpServletResponse response) {
        String ids = request.getParameter("ids");
        var id = ids.split(",");
        try {
            PrintWriter out = response.getWriter();
            for (var ix : id) {
                int i = documentDao.delDocument(Integer.parseInt(ix));
                if (i < 1) {
                    out.print(0);
                    return;
                }
            }
            out.print(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void delDocument(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        try {
            PrintWriter out = response.getWriter();
            Document document=documentDao.findById(id);
            int i = documentDao.delDocument(id);
            if (i > 0) {
                String realpath = request.getSession().getServletContext().getRealPath("/files");
                System.out.println(realpath);
                File dir = new File(realpath);
                File file = new File(dir, document.getFileName());
                if (file.exists()) {
                    System.out.println("exits");
                    file.delete();
                }

                out.print(1);
            } else {
                out.print(0);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private void addDocument(HttpServletRequest request, HttpServletResponse response) {
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String fileName=request.getParameter("filename");
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        System.out.println(title);
        System.out.println(content);
        System.out.println(fileName);
        String[] res=fileName.split("\\.");
        String fileType=res[1];
        String url="/files/"+fileName;
        System.out.println(fileType);
        Document document=new Document(title,content,fileName,fileType,url,user.getId());

        int i = documentDao.addDocument(document);

        try {
            PrintWriter out = response.getWriter();
            if (i > 0) {
                out.print(1);
            } else {
                out.print(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void upload(HttpServletRequest request, HttpServletResponse response) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            String realpath = request.getSession().getServletContext().getRealPath("/files");
            System.out.println(realpath);
            File dir = new File(realpath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");
            try {
                PrintWriter out=response.getWriter();
                List<FileItem> items = upload.parseRequest(request);
                System.out.println(items.size());
                for(var item:items){
                    if(item.isFormField()){
                        String name=item.getFieldName();
                        String value=item.getString("utf-8");
                        System.out.println(name+" "+value);

                    }else{
                        String urlStr=System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf('.'));
                        item.write(new File(dir,urlStr));
                        Map<String,Object> map=new HashMap<>();
                        map.put("url",urlStr);
                        out.print(new Gson().toJson(map));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void documentList(HttpServletRequest request, HttpServletResponse response) {
        //处理乱码问题
        response.setCharacterEncoding("UTF-8");
        //通过响应的response获取打印输出流
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 取出用户输入的条件
            String title = request.getParameter("title");
            //调用查询方法
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            Document document=new Document(title);
            List<Document> documents = documentDao.listDocument(document, page, limit);
            //lauyi框架返回四个参数
            R r = new R();
            r.put("msg", "查询成功");
            r.put("data", documents);
            r.put("count", documentDao.count());
            r.put("code", 0);
            //将对象返回到页面上，响应数据--respons--打印输出流
            out.print(new Gson().toJson(r));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("dopost");
        doGet(request, response);
    }
}
